package com.fengxu.netty.dubborpc.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;


import java.lang.reflect.Proxy;
import java.util.concurrent.*;

public class NettyClient {

    // 创建线程池
    private static ExecutorService threadPool = new ThreadPoolExecutor(2,4,2,
            TimeUnit.SECONDS,new ArrayBlockingQueue(4),Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());

    // 客户端处理器
    private static MyClientHandler clientHandler = null;

    // 编写代理模式,获取代理对象
    public Object getBean(final Class<?> proxyClass,String protocolHead){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{proxyClass},(proxy,method,args)->{
                if(clientHandler == null){
                    initClient();
                }
                clientHandler.setParam(protocolHead+args[0]);
                return threadPool.submit(clientHandler).get();
        });
    }


    // 初始化客户端
    private static void initClient(){
        clientHandler = new MyClientHandler();
        NioEventLoopGroup boosGroup = new NioEventLoopGroup(1);
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(boosGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true) // 设置tcp不延时
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(clientHandler);
                    }
                });
        try {
            bootstrap.connect("127.0.0.1",6666).sync()
                    .channel().closeFuture().sync();
            System.out.println("连接服务器成功!");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("连接服务器成功!");
    }


    // 自定义客户端处理器
    private static class MyClientHandler extends SimpleChannelInboundHandler<String> implements Callable<String>{
        // 上下文对象
        private ChannelHandlerContext handlerContext;
        // 获取到的结果
        private String result;
        // 要执行方法的参数
        private String param;

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            handlerContext = ctx;
        }

        @Override
        protected synchronized void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
            result = msg;
            notify();
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            System.out.println(cause.getMessage());
            ctx.close();
        }

        // 发送信息给服务器 -> wait -> 等待被唤醒 -> 返回结果
        @Override
        public synchronized String call() throws Exception {
            handlerContext.writeAndFlush(param);
            // 等待channelRead0得到结果后会唤醒线程
            wait();
            return result;
        }

        public void setParam(String param){
            this.param = param;
        }
    }
}
